<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
       <button onclick="dingyue1()">订阅1</button>  | <button onclick="dingyue2()">订阅2</button> | <button onclick="send('你好有兴趣聊聊吗')">发布消息</button>
</body>
<script>
    let bus = {
        list:[],
        on(name,callBack){
            let obj = {
                name,
                callBack
            }
            // 先判断一下当前订阅者列表中是否已存在该订阅者用户
           let index = this.list.findIndex((item)=>item.name === name);
           if(index!==-1){
             return
           }
           this.list.push(obj)
        },
        emit(name,msg){
            // 根据当前name查询到 name所对应的callback
            let index = this.list.findIndex((item)=>item.name===name);
            if(index!==-1){
                this.list[index].callBack(msg)
            }
        }
    }
    function dingyue1(){
        // 参数一订阅者名称  参数二订阅者回调函数
        bus.on("one",(msg)=>{
            alert(msg)
            console.log(msg)
        })
    }
    function dingyue2(){
        bus.on("two",(msg)=>{
            alert(msg)
            console.log(msg)
        })
    }
    function send(msg){
        // 参数一 订阅者名称 参数二 发布的消息
        bus.emit("two",msg)
    }
</script>
</html>